package com.varteq.progress.server.io;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public final class ProgressInputStream extends FilterInputStream {
	private List<IProgressListener> _listeners;
	private long _bytesRead = 0;
	private long _totalBytes = 0;

	public ProgressInputStream(final InputStream in, final long totalBytes) {
		super(in);
		this._totalBytes = totalBytes;
		_listeners = new ArrayList<IProgressListener>();
	}

	public void addListener(final IProgressListener listener) {
		_listeners.add(listener);
	}

	@Override
	public int read() throws IOException {
		int b = super.read();
		this._bytesRead++;
		updateListeners(_bytesRead, _totalBytes);
		return b;
	}

	@Override
	public int read(final byte b[]) throws IOException {
		return read(b, 0, b.length);
	}

	@Override
	public int read(final byte b[], final int off, final int len) throws IOException {
		int bytesRead = in.read(b, off, len);
		this._bytesRead = this._bytesRead + bytesRead;
		updateListeners(this._bytesRead, _totalBytes);
		return bytesRead;
	}

	@Override
	public void close() throws IOException {
		super.close();
		updateListeners(_totalBytes, _totalBytes);
	}

	private void updateListeners(final long bytesRead, final long totalBytes) {
		for (IProgressListener listener : _listeners) {
			listener.update(bytesRead, totalBytes, _listeners.size());
			// System.out.println((double) bytesRead / totalBytes);
		}
	}
}
